import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button } from 'antd';
import React, { useRef, useState } from 'react';
import { columns } from '../data';
import { goodsList, userMsg } from '../service';
import BasicModal from './Modal';

export default function BasicTable() {
  const [visible, setVisible] = useState(false);
  const [user, setUser] = useState({});
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState(true);

  const reloadTable = () => {
    actionRef.current?.reload();
  };

  const getUsers = async (params: any) => {
    const res = await goodsList(params);

    setLoading(false);
    return {
      data: res.data,
      success: true,
      total: res.meta.pagination.total,
    };
  };

  const handleCreate = () => {
    setVisible(true);
  };
  const handleCancel = () => {
    setUser({});
    reloadTable();
    setVisible(false);
  };

  const editUser = async (id: string) => {
    const res = await userMsg(id);
    setVisible(true);
    setUser(res);
  };

  const actionColumn: ProColumns[] = [
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (_: any, record: any) => [
        <a
          key="editable"
          onClick={() => {
            editUser(record.id);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];

  const tableColumn: ProColumns[] = [...columns, ...actionColumn];
  return (
    <>
      <ProTable
        columns={tableColumn}
        actionRef={actionRef} // actionRef 自定义操作表格，例如刷新表格
        cardBordered
        request={async (param) => await getUsers(param)}
        rowKey="id"
        pagination={{
          pageSize: 10,
        }}
        headerTitle="用户列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={handleCreate}
            loading={loading}
          >
            新建
          </Button>,
        ]}
      />
      <BasicModal visible={visible} handleCancel={handleCancel} user={user} />
    </>
  );
}
